<template>
	<view class="wrapper bg-linear h-full">
		<!-- 页面标题 -->
		<view class="p-b-12 flex-s-c">
			<view class="title-symbol"></view>
			<view class="t-bold p-l-6">专升本院校</view>
		</view>

		<!-- 加载状态显示 -->
		<view v-if="isLoading" class="loading-container">
			<text class="loading-text">加载中...</text>
		</view>

		<!-- 错误状态显示 -->
		<view v-else-if="isError" class="error-container">
			<text class="error-text">加载数据失败，请重试</text>
			<button class="retry-btn" @click="fetchSchoolList">重试</button>
		</view>

		<!-- 空状态显示 -->
		<view v-else-if="schools.length === 0" class="empty-container">
			<text class="empty-text">暂无院校数据</text>
			<text v-if="debugMsg" class="debug-text">{{ debugMsg }}</text>
		</view>

		<!-- 列表内容 -->
		<view v-else>
			<ppl-list :list="schools" @toDetail="toDetail" />
		</view>
	</view>
</template>

<script setup>
	import {
		onLoad,
		onShow
	} from '@dcloudio/uni-app';
	import {
		ref,
		onMounted
	} from 'vue';
	import {
		getZsbSchool
	} from '@/package/api/selList.js';

	// 状态管理
	const cid = ref('');
	const schools = ref([]);
	const isLoading = ref(true);
	const isError = ref(false);
	const debugMsg = ref(''); // 调试信息显示

	// 院校列表查询
	const fetchSchoolList = async (pageNo = 1, pageSize = 20) => {
		isLoading.value = true;
		isError.value = false;
		debugMsg.value = '正在加载数据...';

		// 从本地存储获取school_id
		const schoolId = uni.getStorageSync('school_id');
		if (!schoolId) {
			uni.showToast({
				title: '未获取到学校ID',
				icon: 'none'
			});
			debugMsg.value = '未获取到学校ID';
			isLoading.value = false;
			isError.value = true;
			return;
		}

		try {
			uni.showLoading({
				title: '加载中...'
			});
			console.log(`请求第${pageNo}页，每页${pageSize}条`);

			// 调用API获取数据
			const response = await getZsbSchool({
				schoolId,
				page: pageNo,
				pageSize
			});

			// 调试：打印完整响应
			console.log('API原始响应:', response);

			if (response.code === 200 && response.data) {
				const pageData = response.data || [];

				// 数据映射处理（增强健壮性）
				const formattedData = pageData.map(item => {
					if (!item) return null; // 防御性编程

					return {
						id: item.id !== undefined ? item.id : `school_${item.schoolId || 'unknown'}`,
						title: item.title || '未命名学校',
						image: item.image || 'https://picsum.photos/400/300',
						description: item.description || '暂无学校简介',
						schoolId: item.schoolId || '未知ID',
						createdAt: item.createdAt || '未知时间',
						updatedAt: item.updatedAt || '未知时间',
						qrCode: item.qrCode || 'https://picsum.photos/200/200' // 添加二维码字段
					};
				}).filter(item => item); // 过滤null项

				// 调试：检查格式化后数据
				console.log('格式化后数据:', formattedData);
				debugMsg.value = `成功获取${formattedData.length}条数据`;
				schools.value = formattedData;
				isLoading.value = false;
			} else {
				uni.showToast({
					title: '获取数据失败',
					icon: 'none'
				});
				debugMsg.value = '获取数据失败';
				isLoading.value = false;
				isError.value = true;
			}
		} catch (error) {
			console.error('请求异常:', error);
			uni.showToast({
				title: '网络错误，请重试',
				icon: 'none'
			});
			debugMsg.value = '网络请求异常';
			isLoading.value = false;
			isError.value = true;
		} finally {
			uni.hideLoading();
		}
	};

	// 跳转详情页并存储数据
	const toDetail = (schoolId) => {
		console.log(schoolId)
		// 查找对应的学校信息
		const school = schools.value.find(item => item.id === schoolId);
		console.log(schools.value)

		if (school) {
			// 按照详情页所需格式组织数据
			const detailData = {
				title: school.title,
				desc: school.description,
				qrcodes: [{
					url: school.qrCode,
					desc: '详情添加二维码了解'
				}]
			};

			// 存储到本地
			uni.setStorageSync('schoolDetail', detailData);

			// 跳转到详情页
			uni.navigateTo({
				url: '/package/pages/upgradeDetail/upgradeDetail'
			});
		} else {
			uni.showToast({
				title: '未找到学校信息',
				icon: 'none'
			});
		}
	};

	// 生命周期函数
	onLoad((options) => {
		cid.value = options.cid || '';
		debugMsg.value = '页面加载完成';
		fetchSchoolList();
	});

	onShow(() => {
		fetchSchoolList();
		debugMsg.value = '页面显示，触发数据加载';
	});

	onMounted(() => {
		debugMsg.value = '组件挂载完成，触发首次加载';
	});
</script>

<style scoped>
	.wrapper {
		padding: 20rpx;
	}

	.bg-linear {
		background: linear-gradient(to bottom, #f5f7fa, #e4e9f2);
	}

	.title-symbol {
		width: 6rpx;
		height: 30rpx;
		background-color: #3c91ff;
		border-radius: 3rpx;
	}

	/* 列表组件样式 */
	.loading-container,
	.error-container,
	.empty-container {
		padding: 100rpx 0;
		text-align: center;
	}

	.loading-text,
	.error-text,
	.empty-text {
		font-size: 28rpx;
		color: #999;
	}

	.debug-text {
		font-size: 24rpx;
		color: #f53f3f;
		display: block;
		margin-top: 10rpx;
	}

	.retry-btn {
		margin-top: 20rpx;
		padding: 10rpx 30rpx;
		background-color: #3c91ff;
		color: #fff;
		border-radius: 10rpx;
		font-size: 24rpx;
	}
</style>